package com.zzyl.nursing.service.impl;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.IdcardUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.CodeGenerator;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.*;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-01-02
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    /**
     * 入住申请
     *
     * @param dto checkInApplyDto
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void apply(CheckInApplyDto dto) {
        // 1.判断老人是否已入住
        //根据身份证号查询老人
        LambdaQueryWrapper<Elder> elderQueryWrapper = new LambdaQueryWrapper<>();
        CheckInElderDto checkInElderDto = dto.getCheckInElderDto();
        elderQueryWrapper.eq(Elder::getIdCardNo, checkInElderDto.getIdCardNo())
                .in(Elder::getStatus,1,4);
        Elder elder = elderMapper.selectOne(elderQueryWrapper);
        if (ObjectUtils.isNotEmpty(elder)){
            throw new BaseException("老人已入住");
        }

        // 2.更新床位状态为已入住
        Long bedId = dto.getCheckInConfigDto().getBedId();
        Bed bed = bedMapper.selectById(bedId);
        bed.setBedStatus(1);
        bedMapper.updateById(bed);

        // 3.新增或更新老人基本信息
        elder = insertOrUpdateElder(checkInElderDto, bed);

        // 4.新增签约办理
        insertContract(elder, dto.getCheckInConfigDto(), dto.getCheckInContractDto());

        // 5.新增入住信息（同时保存家属信息到remark字段
        CheckIn checkIn = insertCheckInInfo(elder, bed, dto.getElderFamilyDtoList(), dto.getCheckInConfigDto());

        // 6.新增入住配置
        insertCheckInConfig(checkIn, dto.getCheckInConfigDto());
    }

    /**
     * 新增入住配置
     * @param checkIn 入住信息
     * @param checkInConfigDto 入住配置信息
     */
    private void insertCheckInConfig(CheckIn checkIn, CheckInConfigDto checkInConfigDto) {
        CheckInConfig checkInconfig = new CheckInConfig();
        checkInconfig.setCheckInId(checkIn.getId());
        BeanUtils.copyProperties(checkInConfigDto, checkInconfig);
        checkInConfigMapper.insert(checkInconfig);
    }

    /**
     * 新增入住信息
     * @param elder 老人信息
     * @param bed 床位信息
     * @param elderFamilyDtoList 家属信息
     * @param checkInConfigDto 配置信息
     */
    private CheckIn insertCheckInInfo(Elder elder, Bed bed, List<ElderFamilyDto> elderFamilyDtoList, CheckInConfigDto checkInConfigDto) {
        CheckIn checkIn = new CheckIn();
//        BeanUtils.copyProperties(elder, checkIn);
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInConfigDto.getStartDate());
        checkIn.setEndDate(checkInConfigDto.getEndDate());
        checkIn.setNursingLevelName(checkInConfigDto.getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        // 添加家属信息
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));

        checkInMapper.insert(checkIn);
        return checkIn;
    }

    /**
     * 新增签约办理
     * @param elder 老人信息
     * @param checkInConfigDto 入住配置信息
     * @param checkInContractDto 签约办理信息
     */
    private void insertContract(Elder elder, CheckInConfigDto checkInConfigDto, CheckInContractDto checkInContractDto) {
        Contract contract = new Contract();
        contract.setElderId(elder.getId().intValue());
        BeanUtils.copyProperties(checkInContractDto, contract);
        contract.setContractNumber(CodeGenerator.generateContractNumber());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInConfigDto.getStartDate());
        contract.setEndDate(checkInConfigDto.getEndDate());

        contractMapper.insert(contract);
    }

    /**
     * 新增或更新老人基本信息
     */
    private Elder insertOrUpdateElder(CheckInElderDto checkInElderDto, Bed bed) {
        // 判断新增还是更新老人，最后回传老人信息
        String idCardNo = checkInElderDto.getIdCardNo();
        LambdaQueryWrapper<Elder> warpper = new LambdaQueryWrapper<>();
        warpper.eq(Elder::getIdCardNo,idCardNo);
        Elder elder = elderMapper.selectOne(warpper);
        if (ObjectUtils.isNotEmpty(elder)){
            // 更人老人信息
            elder.setStatus(1); // 更新状态为1
            // 更新前端传过来的其他基本信息
            BeanUtils.copyProperties(checkInElderDto,elder);
            // 更新床位信息
            elder.setBedId(bed.getId());
            elder.setBedNumber(bed.getBedNumber());
            elderMapper.updateById(elder);
        } else {
            // 新增老人信息
            elder = new Elder();
            elder.setStatus(1);
            BeanUtils.copyProperties(checkInElderDto,elder);
            elder.setBedId(bed.getId());
            elder.setBedNumber(bed.getBedNumber());
            elderMapper.insert(elder);
        }
        return elder;
    }

    /**
     * 入住详情
     *
     * @param id 入住id
     * @return 结果
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        // 1.查询入住信息
        CheckIn checkIn = checkInMapper.selectById(id);

        // 2.查询老人信息
        Elder elder = elderMapper.selectById(checkIn.getElderId());
        CheckInElderVo checkInElderVo = new CheckInElderVo();
        if (ObjectUtils.isNotEmpty(elder)){
            BeanUtils.copyProperties(elder, checkInElderVo);
            checkInElderVo.setAge(IdcardUtil.getAgeByIdCard(elder.getIdCardNo()));
        }else{
            return null;
        }


        // 3.查询合同
//        Contract contract = contractMapper.selectContractByElderId(checkIn.getElderId());
        Contract contract = contractMapper.selectOne(new LambdaQueryWrapper<Contract>().eq(Contract::getElderId, elder.getId()));

        // 4.查询入住配置
//        CheckInConfig checkInConfig = checkInConfigMapper.selectCheckInConfigByCheckInId(checkIn.getId());
        CheckInConfig checkInConfig = checkInConfigMapper.selectOne(new LambdaQueryWrapper<CheckInConfig>().eq(CheckInConfig::getCheckInId, checkIn.getId()));
        CheckInConfigVo checkInConfigVo = new CheckInConfigVo();
        if(ObjectUtils.isNotEmpty(checkInConfig)){
            BeanUtils.copyProperties(checkInConfig, checkInConfigVo);
            checkInConfigVo.setStartDate(checkIn.getStartDate());
            checkInConfigVo.setEndDate(checkIn.getEndDate());
            checkInConfigVo.setBedNumber(checkIn.getBedNumber());
        }


        // 5.转换家属列表
        List<ElderFamilyVo> elderFamilyVoList = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);

        // 6.整合数据返回
        CheckInDetailVo checkInDetailVo = new CheckInDetailVo();
        checkInDetailVo.setCheckInElderVo(checkInElderVo);
        checkInDetailVo.setElderFamilyVoList(elderFamilyVoList);
        checkInDetailVo.setCheckInConfigVo(checkInConfigVo);
        checkInDetailVo.setContract(contract);
        return checkInDetailVo;
    }
}
